#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:Vergil
# datetime:2018/9/23 22:15
# software: PyCharm
import logging
import time

import requests
import re

logger = logging.getLogger('main.p_collect')


def course_choose(driver, course_name):
    try:
        course_id = driver.find_element_by_xpath("//a[contains(@title,'%s')]" % course_name).get_attribute(
            'data-3')
        class_id = driver.find_element_by_xpath("//a[contains(@title,'%s')]" % course_name).get_attribute(
            'data-4')

        logger.info('----已成功获取课程id----')
        return [course_id, class_id]

    except Exception:
        logger.info('------未获取到课程id------')
        name = input('课程：')
        course_choose(driver, name)


def get_tree_point(course_id, headers):
    url = 'https://spoc.tfswufe.edu.cn/JiaoXue/CourseKnowledgePoint/GetKnowledgePoint'
    data = {'courseId': course_id}
    r = requests.post(url, data=data, headers=headers)
    content = str(r.content, 'utf-8')
    tree_point_lst = re.findall(r'\W(\d{5})\W', content)

    return tree_point_lst


def get_file_list(headers, tree_point_lst, course_id, class_id):
    file_id_lst = []
    url = 'https://spoc.tfswufe.edu.cn/JiaoXue/CourseKnowledgePoint/StudentGetKnowledgePointCourseware?treePoint={tree_point}&courseId={course_id}&classId={class_id}&pageIndex=1'
    for tree_point in tree_point_lst:
        try:
            response = requests.get(
                url.format(
                    tree_point=tree_point,
                    course_id=course_id,
                    class_id=class_id),
                    headers=headers)

            id_lst = re.findall(
                r'<a href="javascript:" style="width:20px" onclick="getNote(.*?)">查看笔记</a>',
                response.text,
                re.S)
            for id in id_lst:
                if id != '':
                    file_id_lst.append(re.findall(r'\d+', id)[0])

        except Exception as e:
            logger.exception(e)

    return file_id_lst


def main(driver, headers, course_name):
    ids = course_choose(driver, course_name)
    course_id = ids[0]
    class_id = ids[1]

    tree_point_lst = get_tree_point(course_id, headers)
    file_id_lst = get_file_list(headers, tree_point_lst, course_id, class_id)

    return [file_id_lst, course_id, class_id]
